/*  This file is a part of JJSched source code
    JJSched - Java Jabber Scheduler - a simple Jabber scheduling application
    Copyright (C) 2008 Cestmir "CZestmyr" Houska

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/> */

package czestmyr.jjsched;

import java.io.*;
import java.nio.channels.*;
import java.util.*;

/**
 * Handles master console input
 */
public class Console extends Thread {
	Console (CommandParser p, ActionExecutor ae, Macros m) {
		theExecutor = ae;
		theParser = p;
		theMacros = m;

		reader = new BufferedReader(
				 new InputStreamReader(
				 Channels.newInputStream(
				 (new FileInputStream(FileDescriptor.in)).getChannel())));
		doContinue = true;

		//Set the thread name for easier identification
		setName("JJSched console thread");
		//Lower the priority of this thread
		setPriority(4);
	}

	/**
	 * Processes the console input by reading System.in
	 */
	public void run() {
		System.out.println("Welcome to jjsched console. Type 'help' for standard command help.");

		while (doContinue) {
			String line = "";
			try {
				line = reader.readLine();
			} catch (Exception e) {
				continue;
			}

			LinkedList<String> tokens = StringParser.parseLine(line);

	        //Macro expansion
    	    ListIterator it = tokens.listIterator(0);
        	while (it.hasNext()){
            	String token = (String)it.next();
	            if (theMacros.isMacro(token)){
    	            it.remove();
        	        Iterator macroit = theMacros.getMacroBody(token).iterator();
            	    while (macroit.hasNext()){
                	    it.add((String)macroit.next());
	                }
    	        }
			}

			Action action = theParser.parse(tokens, "console", "console");
			theExecutor.execute(action);

		}
	}

	/**
	 * Stops the console
	 */
	public void discontinue() {
		doContinue = false;
		this.interrupt();
	}

	private ActionExecutor theExecutor;
	private CommandParser theParser;
	private Macros theMacros;

	private boolean doContinue;

	private BufferedReader reader;
}

